package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author panweiwei
 */
@RestController
@RequestMapping("/user")
@Validated
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户注册
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^.{2,16}$") String username, @Pattern(regexp = "^[a-zA-Z0-9]{2,16}$") String password) {
        log.info("用户名:{},密码:{}", username, password);
        //判断用户名是否在数据库中存在
        User user = userService.findByUserName(username);
        if (user != null) {
            return Result.error("用户名已存在");
        } else {
            //说明用户名不存在 开始注册
            return userService.register(username, password);
        }
    }

    /**
     * 登陆
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^.{2,16}$") String username, @Pattern(regexp = "^[a-zA-Z0-9]{2,16}$") String password) {
        //查询用户信息是否存在
        User user = userService.findByUserName(username);
        if (user == null) {
            return Result.error("用户名不存在");
        }
        //判断密码是否正确
        if (Md5Util.getMD5String(password).equals(user.getPassword())) {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username", user.getUsername());
            String token = JwtUtil.genToken(claims);
            log.info("JWT Token:{}", token);
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 1, TimeUnit.HOURS);
            log.info("result:{}",Result.success(token));
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
        //从token中获取用户信息
//        Map<String, Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        log.info("用户信息:{}", user);
        return Result.success(user);
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        Boolean b = userService.update(user);
        log.info("b:{}", b);
        return Result.success();
    }

    /**
     * 更新用户头像
     *
     * @param avatarUrl 头像地址
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 更新用户密码
     *
     * @param params
     * @return
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody HashMap<String, String> params, @RequestHeader("Authorization") String token) {
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("参数异常");
        }

        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        String password = user.getPassword();
        if (!password.equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码不正确");
        }
        if (!newPwd.equals(rePwd)) {
            return Result.error("两次密码不一致");
        }
        //修改密码
        userService.updatePwd(newPwd, user.getId());
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}
